package com.finalx.timersms;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;

public class VibratorService extends Service {  
    private static final String TAG = "VibratorService";  
    
	Vibrator mVibrator = null;
	boolean mVibrating = false;
	long[] vibratePattern = {0, VibratorActivity.VIBRATE_TOTAL_TIME/2 , VibratorActivity.VIBRATE_TOTAL_TIME/2};
	int   vibrateRepeat = 0;
	boolean threadEnabled = false;
    
    private ServiceBinder serviceBinder = new ServiceBinder();
    public class ServiceBinder extends Binder implements IVibrateRate {
		public void set(long timeVibrate, long timeIdle) {
			// TODO Auto-generated method stub
			vibratePattern[1] = timeVibrate;
			vibratePattern[2] = timeIdle;
		}

		public void on() {
			// TODO Auto-generated method stub
			startVibrate();
		}

		public void off() {
			// TODO Auto-generated method stub
			stopVibrate();
		}

		public boolean isOn() {
			// TODO Auto-generated method stub
			return mVibrating;
		}
	}
    
	public class VibrateThread extends Thread{
		public void run() {
			standAloneVibrate();
		}
	}
	
	public void standAloneVibrate() {
		mVibrating = true;
		mVibrator.vibrate(vibratePattern, vibrateRepeat);
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return serviceBinder;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		Log.d(TAG, "onCreate() called");
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.d(TAG, "onDestroy() called");
	}
	

	public void startVibrate() {
    	if(mVibrating) {
    		return;
    	}
    	Log.d(TAG, "start vibrate ++++++");
    	if(threadEnabled) {
	    	VibrateThread mVibrateThread = new VibrateThread();
	    	mVibrateThread.start();
    	} else {
    		standAloneVibrate();
    	}
    }
    
    public void stopVibrate() {
    	Log.d(TAG, "stop vibrate ------");
    	mVibrating = false;
    	mVibrator.cancel();
    }
	
}  
